<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">	
<title>领料管理的添加页面</title>
<%@ include file="common.jsp"%>
<script type="text/javascript">
$(function() {
	$(".form_datetime").datetimepicker({
		/* 显示格式 */       
		format: "yyyy-mm-dd",
	    /* 完成关闭 */
	    autoclose: true,
	   	/* 今天 时间按钮*/
	    todayBtn: true, 
	   	/* 今天的时间变黄色 */
	    todayHighlight:true, 
	    /* 定位 */
	    pickerPosition: "bottom-left",
	    /* 最小值 */
	    minuteStep: 10,
	    /*  语言 */
	    language: 'zh-CN',  
		/* 分上午下午 */
	    showMeridian: true,
	    /* 分的所有 */
	    minuteStep:true,
	    startView: 2,//月视图
		minView: 2//日期时间选择器所能够提供的最精确的时间选择视图
	}).on('hide',function(e) {  
		e.stopPropagation(); //e.stopPropagation()阻止事件冒泡
	});
});
</script>
<script type="text/javascript">
	$(function() {
		//1.初始化Table
		var oTable = new TableInit();
		oTable.Init();
		//2.初始化Button的点击事件
		var oButtonInit = new ButtonInit();
		oButtonInit.Init();
		//初始化领料人下拉框
		getStaff();
		//点击查询按钮事件
		$("#btn_query").click(
			function() {
				if ($("#endDate").val() == '' || $("#endDate").val() == null) {
					var now = new Date();
					var year = now.getFullYear(); //年
					var month = now.getMonth() + 1; //月
					var day = now.getDate(); //日
					var time = year + "-" + month + "-" + day;
					$("#endDate").val(time);
				}
				$("#paichan").bootstrapTable('refresh',{
						url : '${pageContext.request.contextPath }/mater/selectDetail.do?'
							});
			});
	});
	var TableInit = function() {
		var oTableInit = new Object();
		//初始化Table
		oTableInit.Init = function() {
			$('#paichan').bootstrapTable({
				method : 'get', //请求方式（*）
				toolbar : '#toolbar', //工具按钮用哪个容器
				pagination : true, //是否显示分页（*）
				striped : true, //是否显示行间隔色
				sortable : false, //是否启用排序
				sortOrder : "asc", //排序方式
				queryParams : oTableInit.queryParams,//传递参数（*）
				sidePagination : "server", //分页方式：client客户端分页，server服务端分页（*）
				pageNumber : 1, //初始化加载第一页，默认第一页
				pageSize : 10, //每页的记录行数（*）
				pageList : [ 10, 20, 30 ], //可供选择的每页的行数（*）
				strictSearch : true,
				clickToSelect : true, //是否启用点击选中行
				height : 300, //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
				uniqueId : "ID", //每一行的唯一标识，一般为主键列
				detailView : false, //是否显示父子表
				columns : [ {
					checkbox : true
				}, {
					field : 'id'
				}, {
					field : 'remark1',
					align : 'center',
					title : '排产单号'
				}, {
					field : 'pnum',
					align : 'center',
					title : '品编'
				}, {
					field : 'pname',
					align : 'center',
					title : '品名'
				}, {
					field : 'plannum',
					align : 'center',
					title : '生产量'
				} ]
			});
			$('#paichan').bootstrapTable('hideColumn', 'id');
			/* 初始化一个Table，这个就是BOM了 */
		    $('#bomDetail').bootstrapTable({
				method : 'get', //请求方式（*）
				striped : true, //是否显示行间隔色
				cache : false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
				pagination : true, //是否显示分页（*）
				sortable : false, //是否启用排序
				sortOrder : "asc", //排序方式
				queryParams : oTableInit.queryParams,//传递参数（*）
				sidePagination : "server", //分页方式：client客户端分页，server服务端分页（*）
				pageNumber : 1, //初始化加载第一页，默认第一页
				pageSize : 10, //每页的记录行数（*）
				pageList : [ 10, 20, 30 ], //可供选择的每页的行数（*）
				clickToSelect : true, //是否启用点击选中行
				height : 450, //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
				uniqueId : "ID", //每一行的唯一标识，一般为主键列
				detailView : false, //是否显示父子表
				columns : [ {
					field : 'materialName',
					align : 'center',
					title : '物料名称'
				}, {
					field : 'remark01',
					align : 'center',
					title : '型号'
				}, {
					field : 'materialUnit',
					align : 'center',
					title : '计量单位'
				}, {
					field : 'requireCount',
					align : 'center',
					title : '需求数量'
				}, {
					field : 'remark03',
					align : 'center',
					title : '最高安全库存'
				}, {
					field : 'remark04',
					align : 'center',
					title : '最低安全库存'
				}, {
					field : 'xianbianCount',
					align : 'center',
					title : '线边库库存'
				}, {
					field : 'lingliaoRequireCount',
					align : 'center',
					title : '应领料量'
				}],
		    });
		};
		//得到查询的参数
		oTableInit.queryParams = function(params) {
			var temp = { //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
				limit : params.limit, //页面大小
				offset : params.offset,
				stattime : $("#startDate").val(),
				endtime : $("#endDate").val()
			};
			return temp;
		};
		return oTableInit;
	};
	var ButtonInit = function() {
		var oInit = new Object();
		var postdata = {};

		oInit.Init = function() {
			//初始化页面上面的按钮事件
		};
		return oInit;
	};
	//领料人下拉框--只能显示职位为生产管理的人名
	function getStaff(){
		$.ajax({
			type:"post",
			url:"${pageContext.request.contextPath }/mater/selName.do",
			success:function(data){
				var str = "<option value = ''>--请选择--</option>";
				var json = eval('('+data+')');
				for(var i = 0;i < json.rows.length;i++){
					var staffname = json.rows[i].staffname;
					str += '<option value = "'+staffname+'">'+staffname+'</option>';
				}
					$("#pickMan").append(str);
					$("#pickMan").selectpicker('refresh');
			}
		});
	}
	//查询排产单
	function fun2() {
		$("#formSearch")[0].reset();
		$("#acquisitionTime").find("option[value = '0']").attr("selected",true);
		$("#paichandan").modal('show');
		$('#paichandan').on('shown.bs.modal', function () {
			$("#paichan").bootstrapTable('refresh',{
				url : '${pageContext.request.contextPath }/mater/selectDetail.do'
				});
		});
	}
	//添加
	function fun3() {
		var pickMan = $("#pickMan").val();
		var pickDate = $("#pickDate").val();
		if(pickMan == "" || pickMan == null || pickDate == "" || pickDate == null){
			toastr.error('请将信息填写完整');
		}else{
			var url = "${pageContext.request.contextPath }/mater/insert.do?id="+id;
			$.post(url,$("#addForm").serialize(),
				function(data) {
					if (data == 1) {
						toastr.success('添加成功');
						setTimeout(function(){
							window.location = "${pageContext.request.contextPath }/pages/hy/lingliao.jsp";
						},1000);
					} else {
						toastr.error('保存失败');
				}
			});
		}
	}
	//近几个月的选择
	function changeSelect() {
		$("#endDate").val(CurentTime());
		var dm = $("#acquisitionTime").val();
		if (dm == "1") {
			$("#startDate").val(changeTime1());
		} else if (dm == "3") {
			$("#startDate").val(changeTime3());
		} else {
			$("#startDate").val(null);
			$("#endDate").val(null);
		}
	}
	//获取当前时间
	function CurentTime() {
		var now = new Date();
		var year = now.getFullYear(); //年
		var month = now.getMonth() + 1; //月
		if(month < 10){
			month = "0" + month;
		}
		var day = now.getDate(); //日
		if(day < 10){
			day = "0" + day;
		}
		var time = year + "-" + month + "-" + day;
		return time;
	}
	//选择近3个月
	function changeTime3() {
		var now = new Date();
		var year = now.getFullYear(); //年
		var month = 0;
		if (now.getMonth() == 2) {
			month = 12;
			year = year - 1;
		} else if (now.getMonth() == 1) {
			month = 11;
			year = year - 1;
		} else if (now.getMonth() == 0) {
			month = 10;
			year = year - 1;
		} else {
			month = now.getMonth() - 2; //月
			if(month < 10){
				month = "0" + month;
			}
		}
		var day = now.getDate(); //日
		if(day < 10){
			day = "0" + day;
		}
		var time = year + "-" + month + "-" + day;
		return time;
	}
	function changeTime1() {
		var now = new Date();
		var year = now.getFullYear(); //年
		var month = 0;
		if (now.getMonth() == 0) {
			month = 12;
			year = year - 1;
		} else {
			month = now.getMonth(); //月
		if(month < 10){
			month = "0" + month;
		}
		}
		var day = now.getDate(); //日
		if(day < 10){
			day = "0" + day;
		}
		var time = year + "-" + month + "-" + day;
		return time;
	}
	
	// 定义一个数组保存选中的物料编号
	var pNumArr;
	var lingliaoOrder;
	var plannum;
	var id = "";
	/* 点击“BOM清单”按钮后的事件 */
	function saveData(){
		pNumArr = new Array();
		/* 先将选中的排产单信息用来查询BOM表 */
		var pNum = $('#paichan').bootstrapTable('getSelections');
	    for ( var i = 0; i < pNum.length; i++) {
	    		pNumArr.push(pNum[i].pnum);
	    		plannum = pNum[i].plannum;
	    		id += (pNum[i].id) + ",";
		}
	 	// 将产品编号数组当做参数传递到后台
	    $.ajax({
	        type: "post",
	        dataType: "json",
	        url: '${pageContext.request.contextPath }/mater/bom.do',
	        // 数组和产品名称作为参数
	        data:{"pNummArr":pNumArr,"lingliaoOrdNum":$("#pickOdd").val(), "plannum":plannum,"id":id},
	        success: function (data) {
	            if (data == 1) {
	                toastr.success('BOM计算完成');
	            }else{
	            	toastr.error('BOM计算异常');
	            }
	            $("#bomDetail").bootstrapTable("refresh",{
	    			url:"${pageContext.request.contextPath }/mater/selectDet.do?remark02="+ $("#pickOdd").val()
	    		});
	        }
	    });
	 	// 给“排产单号”输入框赋值 
	    var getSelect = $('#paichan').bootstrapTable('getSelections');
	    var stringBuilder = [];
	    for ( var int = 0; int < getSelect.length; int++) {
			stringBuilder.push(getSelect[int].remark1);
		}
	    	$("#schedOdd").val("");
	    	$("#schedOdd").val(stringBuilder.toString());
	 	/* 点击后模态框隐藏 */
	    $("#paichandan").modal("toggle");
	}
	toastr.options.positionClass = 'toast-top-center';
</script>
<style type="text/css">
	.mytitile {
		width: 100%;
		float: left;
		height: 30px;
		background-color: #E0E0E0;
		margin-bottom: 5px;
	}
	.form-horizontal .form-group{
		margin-right: 0px;
    	margin-left: 0px;
	}
	font {
		color: black;
		font-size: 24px;
	}
</style>
</head>
<body>
	<br>
	<div>
		<div class="mytitile">
			<font>新增领料单</font>
		</div>
		<label style="margin-left: 50px; font-size: 20px; margin-top: -10px;"></label>
		<form class="form-horizontal" role="form" id="addForm">
			<div class="form-group">
				<div style="width: 10%; float: left; margin-top: 15px; margin-right: 10px;" align="right">
					<label>领料单号</label>
				</div>
				<div style="width: 20%; float: left;">
					<input type="text" class="form-control" readonly="readonly" style="margin-top: 10px;" 
						value="${odd}" id="pickOdd" name="pickOdd">
				</div>
				<div style="width: 10%; float: left; margin-top: 15px; margin-right: 10px;" align="right">
					<label>领料人</label>
				</div>
				<div style="width: 20%; float: left; margin-top: 10px">
					<select id="pickMan" name="pickMan" data-live-search="true" 
						class="selectpicker show-tick form-control">
					</select>
				</div>
			</div>
			<div class="form-group">
				<div style="width: 10%; float: left; margin-top: 25px; margin-right: 10px;" align="right">
					<label>领料时间</label>
				</div>
				<div style="width: 20%; float: left;">
					<input type="text" id="pickDate" name="pickDate" placeholder="yyyy-mm-dd" 
							class="form_datetime form-control" readonly="readonly" style="margin-top: 15px;">
				</div>
				<div style="width: 10%; float: left; margin-top: 25px; margin-right: 10px;" align="right">
					<label>排产单号</label>
				</div>
				<div style="width: 40%; float: left;">
					<input onfocus="fun2()" class="form-control" style="margin-top: 15px;" id="schedOdd" 
						value="" name="schedOdd">
				</div>
			</div>
			<div class="panel panel-info" style="padding-bottom: 0px;" id="detail">
				<div class="panel-heading">
					<h3 class="panel-title">领出物料明细</h3>
				</div>
				<div class="panel-body">
					<table class="table table-bordered" id="bomDetail">
						<thead>
							<tr align="center">
								<th style="text-align:center;" data-align="center" 
									data-field="materialName">物料名称</th>
								<th style="text-align:center;" data-align="center" 
									data-field="remark01">型号</th>
								<th style="text-align:center;" data-align="center" 
									data-field="materialUnit">计量单位</th>
								<th style="text-align:center;" data-align="center" 
									data-field="requireCount">需求数量</th>
								<th style="text-align:center;" data-align="center" 
									data-field="xianbianCount">线边库库存</th>
								<th style="text-align:center;" data-align="center" 
									data-field="remark03">最高安全库存</th>
								<th style="text-align:center;" data-align="center" 
									data-field="remark04">最低安全库存</th>
								<th style="text-align:center;" data-align="center" 
									data-field="lingliaoRequireCount">应领料量</th>
							</tr>
						</thead>
					</table>
				</div>
			</div>
			<div align="right" style="margin-right: 100px;">
				<button type="button" class="btn btn-primary" onclick="fun3()">保存</button>
				<button type="button" class="btn btn-default" 
				onclick="location='${pageContext.request.contextPath }/pages/hy/lingliao.jsp'">取消</button>
			</div>
		</form>
	</div>
	<!-- 排产单模态框 -->
	<div class="modal fade" id="paichandan" tabindex="-1" role="dialog" data-aria-labelledby="detailLabel" 
		data-aria-hidden="true" data-backdrop="static" data-keyboard="false">
		<div class="modal-dialog" style="width: 70%;">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-label="Close" 
						aria-hidden="true">&times;</button>
					<h4 class="modal-title" id="detailLabel">排产单选择</h4>
				</div>
				<div class="modal-body">
					<div class="panel panel-default" id="search1">
						<div class="panel-heading">查询条件</div>
						<div class="panel-body" style="height: 60px;">
							<form id="formSearch" class="form-horizontal">
								<div class="form-group">
									<div class="form-group">
										<label class="control-label col-sm-1" for="acquisitionTime"
											style="width: 200px;">排产单日期:</label>
										<div class="col-sm-3" style="width: 200px;">
											<select class="selectpicker show-tick form-control"
												id="acquisitionTime" onchange="changeSelect()">
												<option value="0">--请选择--</option>
												<option value="1">最近一个月</option>
												<option value="3">最近三个月</option>
											</select>
										</div>
										<label class="control-label col-sm-1" for="startDate"
											style="width: 5px;">从</label>
										<div class="col-sm-3" style="width: 200px;">
											<input type="text" name="startDate" id="startDate"
												lay-verify="date" placeholder="yyyy-mm-dd"
												autocomplete="off" class="form_datetime form-control"
												readonly="readonly" style="height: 34px;">
										</div>
										<label class="control-label col-sm-1" for="endDate"
											style="width: 5px;">至</label>
										<div class="col-sm-3" style="width: 200px;">
											<input type="text" id="endDate" name="endDate"
												placeholder="yyyy-mm-dd" autocomplete="off"
												lay-verify="date" class="form_datetime form-control" readonly="readonly" 
												style="height: 34px;">
										</div>
										<div class="col-sm-2" align="right">
											<button type="button" style="width: 150px; margin-top: -2px;
												margin-right: -50px;" id="btn_query" 
													class="btn btn-primary">查询</button>
										</div>
									</div>
								</div>
							</form>
						</div>
					</div>
					<div>
						<table id="paichan"></table>
					</div>
					<div align="right" style="margin-right: 100px;">
						<button id="btn_bom" type="button" class="btn btn-primary" style="width: 100px;" 
							onclick="saveData()">BOM计算</button>
						&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
						<button id="close" type="button" class="btn btn-primary" 
							data-dismiss="modal">关闭</button>
					</div>
				</div>
			</div>
		</div>
	</div>
</body>
</html>